package yxmes.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import com.xiaoleilu.hutool.thread.ThreadUtil;
import org.yx.utils.Config;

import com.fr.base.FRContext;
import com.fr.dav.LocalEnv;
import com.fr.general.ModuleContext;
import com.fr.io.TemplateWorkBookIO;
import com.fr.io.exporter.ExcelExporter;
import com.fr.io.exporter.ImageExporter;
import com.fr.io.exporter.PDFExporter;
import com.fr.main.TemplateWorkBook;
import com.fr.main.impl.WorkBook;
import com.fr.main.workbook.ResultWorkBook;
import com.fr.report.module.EngineModule;
import com.fr.stable.WriteActor;
import com.xiaoleilu.hutool.collection.CollUtil;
import com.xiaoleilu.hutool.date.DateField;
import com.xiaoleilu.hutool.date.DateTime;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;

public class FineReportUtil {
    private static String envPath = null;
    public final static String filePath = Config.getString("application.service.path").substring(0, 3)
            + Config.getString("application.context.name") + "/";

    public static String getFilePath() {
        return filePath;
    }

    private static String getEnvPath() {
        if (envPath == null) {
            envPath = Config.getString("frHome");
            FRContext.setCurrentEnv(new LocalEnv(envPath));
            FRContext.getLogger().log(Level.ALL, "");
        }

        return envPath;
    }

    public static TemplateWorkBook readTemplate(String templatePath) throws Exception {
        if (StrUtil.isBlank(getEnvPath())) {
            throw new Exception("Please config frHome.");
        }

        return TemplateWorkBookIO.readTemplateWorkBook(FRContext.getCurrentEnv(), templatePath);
    }

    public static File printDataToPdf(Map<String, Object> mapParm, String templateFileName) throws Exception {
        getEnvPath();
        // 模板文件及路径
        if (!StrUtil.endWithIgnoreCase(templateFileName, ".cpt")) {
            templateFileName += ".cpt";
        }

        String domain = Config.getString("frDomain");
        if (StrUtil.isBlank(domain)) {
            domain = Config.getString("application.context.name");
        }
        String filePath = "doc\\" + domain + "\\"
                + (StrUtil.equalsIgnoreCase("DEV", Config.getString("jboot.app.mode")) ? "test\\" : "prod\\") + templateFileName;

        File tmp = createDownloadFile("pdf");// File.createTempFile(RandomUtil.randomString(8),
        // ".pdf");
        FileOutputStream outputStream = new FileOutputStream(tmp);

        try {
            // FRContext.setCurrentEnv(new LocalEnv(getEnvPath()));
            ModuleContext.startModule(EngineModule.class.getName());
            WorkBook frWb = (WorkBook) TemplateWorkBookIO.readTemplateWorkBook(FRContext.getCurrentEnv(), filePath);

            PDFExporter ee = new PDFExporter();
            ResultWorkBook rwb = frWb.execute(mapParm, new WriteActor());
            ee.export(outputStream, rwb);
        } finally {
            ModuleContext.stopModules();
            outputStream.close();
        }

        return tmp;
    }

    public static File printDataToXls(Map<String, Object> mapParm, String templateFileName) throws Exception {
        getEnvPath();
        // 模板文件及路径
        if (!StrUtil.endWithIgnoreCase(templateFileName, ".cpt")) {
            templateFileName += ".cpt";
        }
        String domain = Config.getString("frDomain");
        if (StrUtil.isBlank(domain)) {
            domain = Config.getString("application.context.name");
        }
        String filePath = "doc\\" + domain + "\\"
                + (StrUtil.equalsIgnoreCase("DEV", Config.getString("jboot.app.mode")) ? "test\\" : "prod\\") + templateFileName;

        File tmp = createDownloadFile("xls");//File.createTempFile(RandomUtil.randomString(8), ".pdf");
        FileOutputStream outputStream = new FileOutputStream(tmp);

        try {
            // FRContext.setCurrentEnv(new LocalEnv(getEnvPath()));
            ModuleContext.startModule(EngineModule.class.getName());
            WorkBook frWb = (WorkBook) TemplateWorkBookIO.readTemplateWorkBook(FRContext.getCurrentEnv(), filePath);

            ExcelExporter ee = new ExcelExporter();
            ResultWorkBook rwb = frWb.execute(mapParm, new WriteActor());
            ee.export(outputStream, rwb);
            ModuleContext.stopModules();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            ModuleContext.stopModules();
        }

        return tmp;
    }

    public static File printDataToPng(Map<String, Object> mapParm, String templateFileName) throws Exception {
        getEnvPath();
        // 模板文件及路径
        if (!StrUtil.endWithIgnoreCase(templateFileName, ".cpt")) {
            templateFileName += ".cpt";
        }
        String filePath = "doc\\" + Config.getString("frDomain") + "\\"
                + (StrUtil.equalsIgnoreCase("DEV", Config.getString("mode")) ? "test\\" : "prod\\") + templateFileName;

        File tmp = File.createTempFile(RandomUtil.randomString(8), ".bmp");
        FileOutputStream outputStream = new FileOutputStream(tmp);

        try {
            // FRContext.setCurrentEnv(new LocalEnv(getEnvPath()));
            ModuleContext.startModule(EngineModule.class.getName());
            WorkBook frWb = (WorkBook) TemplateWorkBookIO.readTemplateWorkBook(FRContext.getCurrentEnv(), filePath);

            // SVGExporter ee = new SVGExporter();
            ImageExporter ee = new ImageExporter();
            ResultWorkBook rwb = frWb.execute(mapParm, new WriteActor());
            ee.export(outputStream, rwb);
            ModuleContext.stopModules();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            ModuleContext.stopModules();
        }

        return tmp;
    }

    public static File createDownloadFile(String suffixExt) throws Exception {
        final String filePath = FineReportUtil.filePath;// JFinal.me().getConstants().getBaseDownloadPath()
        // + "/export/";
        ThreadUtil.execute(new Runnable() {
            public void run() {
                List<File> files = FileUtil.loopFiles(filePath);
                Date nowDate = new Date();
                DateTime dt = DateUtil.offsetHour(nowDate, -1);
                if (CollUtil.isNotEmpty(files)) {
                    for (File file : files) {
                        if (FileUtil.isFile(file) && DateUtil.offsetHour(FileUtil.lastModifiedTime(file), 1).compareTo(dt) < 0) {
                            try {
                                FileUtil.del(file);
                            } catch (Exception ignored) {
                            }
                        }
                    }
                }
            }
        });

        return FileUtil.file(filePath + RandomUtil.simpleUUID() + (suffixExt.startsWith(".") ? suffixExt : ("." + suffixExt)));
    }
}
